package com.nycreativity.elecreativity.controller


import com.nycreativity.elecreativity.aop.ValidateAspect
import com.nycreativity.elecreativity.entity.ResultData
import com.nycreativity.elecreativity.entity.cons.CommonURLConstants
import com.nycreativity.elecreativity.entity.enums.OrderStatusEnum
import com.nycreativity.elecreativity.entity.param.ValidateList
import com.nycreativity.elecreativity.entity.param.order.OrderAddParam
import com.nycreativity.elecreativity.entity.param.order.OrderQueryParam
import com.nycreativity.elecreativity.entity.po.Order
import com.nycreativity.elecreativity.entity.vo.PageDataVO
import com.nycreativity.elecreativity.entity.vo.order.OrderItemVO
import com.nycreativity.elecreativity.entity.vo.order.OrderOverviewVO
import com.nycreativity.elecreativity.service.OrderService
import com.nycreativity.elecreativity.util.usersession.UserContext
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime

import javax.annotation.Resource
import javax.validation.Valid

/**
 * <p>
 *  订单前端控制器
 * </p>
 *
 * @author sxt && ttxxi
 * @since 2021-03-11
 */
@RestController
@RequestMapping(CommonURLConstants.ORDER_PREFIX)
@Api(tags = ["订单相关接口"])
class OrderController {

    @Resource
    lateinit var orderService: OrderService

    /**
     * 添加订单
     * @param orderAddParams OrderAddParam
     * @return ResultData<Boolean>
     */
    @PostMapping
    @ApiOperation("添加订单")
    @ValidateAspect.ParamValidate
    fun addOrder(
        @RequestBody @Valid orderAddParams: ValidateList<OrderAddParam>,
        bindingResult: BindingResult
    ): ResultData<Long> {
        val orderId = orderService.addOrder(orderAddParams) ?: return ResultData.FAILED()
        return ResultData.SUCCESS(data = orderId)
    }

    @DeleteMapping("{orderId}")
    @ApiOperation("删除订单")
    fun removeOrder(@PathVariable("orderId") orderIds: Array<Long>): ResultData<Boolean> {
        return if (orderIds.isNotEmpty() && orderService.removeOrder(orderIds))
            ResultData.SUCCESS("订单删除成功")
        else ResultData.FAILED("订单删除失败")
    }

    @GetMapping
    @ApiOperation("查询订单列表")
    fun getOrderList(orderQueryParam: OrderQueryParam): ResultData<PageDataVO<OrderOverviewVO>> {
        val data = orderService.queryOrderOverview(orderQueryParam)
        return ResultData.SUCCESS(data = data)
    }

    @GetMapping("{orderId}")
    @ApiOperation("查询订单商品信息")
    fun getOrderItems(@PathVariable("orderId") orderId: Long): ResultData<List<OrderItemVO>> {
        return ResultData.SUCCESS(data = orderService.queryOrderItems(orderId))
    }

    @PutMapping("{orderId}/{status}")
    @ApiOperation(
        "针对用户的订单签收及退换货申请, 对应的订单状态操作严格按照约定" +
                "(其中, 签收订单操作status传2, 申请换货操作status传3, 申请退货操作status传5)"
    )
    fun exchangeOrReturn(
        @PathVariable("orderId") orderId: Long,
        @PathVariable("status") status: Int
    ): ResultData<Boolean> {
        var result = false
        if (status == OrderStatusEnum.HAS_SIGNED.status
            || status == OrderStatusEnum.EXCHANGING.status
            || status == OrderStatusEnum.GOODS_RETURNING.status
        ) {
            result = orderService.updateById(setOrderStatus(orderId, status))
        }
        return if (result)
            ResultData.SUCCESS(
                OrderStatusEnum.getStatusDes(status)?.des
            )
        else ResultData.FAILED(
            "订单状态设置失败, 可能传入状态不合法"
        )
    }

    @PutMapping("manage/status/{orderId}/{status}")
    @ApiOperation(
        "针对管理员的订单状态修改，注意此接口可修改订单状态为规定范围内的任意状态, 对应的订单状态操作严格按照约定" +
                "(其中, 默认状态为0代表待付款, 签收待签收操作status传1, 签收订单操作status传2, 申请换货操作status传3, " +
                "已换货操作status传4, 申请退货操作status传5)"
    )
    fun manageOrderStatus(
        @PathVariable("orderId") orderId: Long,
        @PathVariable("status") status: Int
    ): ResultData<Boolean> {
        val order = setOrderStatus(
            orderId,
            OrderStatusEnum.getStatusDes(status)?.status
        )
        return if (order != null && orderService.updateById(order)
        ) ResultData.SUCCESS(OrderStatusEnum.getStatusDes(status)?.des)
        else ResultData.FAILED("订单状态设置失败, 可能传入状态不合法")
    }

    @PutMapping("manage/express/{orderId}")
    @ApiOperation("设置运单号")
    fun addExpressNum(@PathVariable("orderId") orderId: Long, expressNum: String): ResultData<Boolean> {
        return if (orderId > 0 && orderService.updateById(
                Order(orderId).apply {
                    modifier = UserContext.get()?.id
                    modifyTime = LocalDateTime.now()
                    this.expressNum = expressNum
                })
        ) ResultData.SUCCESS("运单编号设置成功") else ResultData.FAILED("运单编号设置失败")
    }

    private fun setOrderStatus(orderId: Long, status: Int?): Order? {
        if (status != null) {
            return Order(orderId).apply {
                this.status = status
                modifier = UserContext.get()?.id
                modifyTime = LocalDateTime.now()
            }
        }
        return null
    }
}

